package ssn.daily.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import ssn.common.code.service.CodeService;
import ssn.common.util.FileUtil;
import ssn.daily.service.DailyService;
import ssn.daily.vo.DailyMachineVO;
import ssn.daily.vo.DailyPreVO;
import ssn.daily.vo.DailyVO;
import ssn.inven.vo.InvenVO;
import ssn.servicearea.service.ServiceAreaService;
import egovframework.rte.fdl.cmmn.AbstractServiceImpl;
import egovframework.rte.fdl.property.EgovPropertyService;
import egovframework.rte.fdl.string.EgovStringUtil;

/**  
 * @Class Name : 
 * @Description : 
 * 
 * @author ksh
 * @since 2013. 09.26
 * @version 1.0
 * @see
 */
@SuppressWarnings({"rawtypes","unchecked"})
@Service("dailyService")
public class DailyServiceImpl extends AbstractServiceImpl implements DailyService {
	
	@Resource(name="dailyDAO")
	private DailyDAO dailyDAO; 
	
	@Resource(name = "codeService")
    private CodeService codeService;
	
	@Resource(name = "propertiesService")
    protected EgovPropertyService propertiesService;
	
	@Resource(name = "serviceareaService")
    private ServiceAreaService serviceareaService;
	
	/**
	 * 일지 정보 입력
	 */
	public void insertDailyLog(DailyVO vo) throws Exception{
		if(EgovStringUtil.isNotEmpty(vo.getSdl_dlog_file())){
			vo.setSdl_dlog_file(this.dailyFilemove(vo));
		}
		vo.setSdl_dlog_key(dailyDAO.selectDailyLogPk());
		dailyDAO.insertDailyLog(vo);
		this.insertDailyInvenLog(vo);
		this.insertDailyMachineLog(vo);
	}
	
	/**
	 * 일지 약품 정보 저장
	 * @param vo
	 * @throws Exception
	 */
	public void insertDailyInvenLog(DailyVO vo) throws Exception{
		/*String invenRefKey = propertiesService.getString("scc.codekey.inven");
		List<CodeVO> tempInsertCodeVO = new ArrayList<CodeVO>();
		List<CodeVO> tempUpdateCodeVO = new ArrayList<CodeVO>();
		boolean codeChkInsert = false;
		boolean codeChkUpdate = false;
		int count = 0;
		for(InvenVO tempIV : vo.getInvenVOList()){
			if(EgovStringUtil.isEmpty(tempIV.getSui_code_key())){
				CodeVO tempVO = new CodeVO();
				String codeKey = invenRefKey+EgovDateUtil.getCurrentDateTimeAsString()+count;
				tempVO.setScc_code_key(codeKey);
				tempVO.setScc_code_name(tempIV.getSui_code_name());
				tempVO.setScc_flag_yn("Y");
				tempVO.setScc_ref_key(invenRefKey);
				
				tempIV.setSui_code_key(codeKey);
				tempInsertCodeVO.add(tempVO);
				codeChkInsert = true;
				count++;
			}else{
				CodeVO tempVO = new CodeVO();
				tempVO.setScc_code_key(tempIV.getSui_code_key());
				tempVO.setScc_code_name(tempIV.getSui_code_name());
				tempUpdateCodeVO.add(tempVO);
				codeChkUpdate = true;
			}
		}
		if(codeChkInsert)
			codeService.insertCodeInfo(tempInsertCodeVO);
		
		if(codeChkUpdate)
			codeService.updateCodeInfo(tempUpdateCodeVO);*/
		
		dailyDAO.insertDailyInvenLog(vo);
	}
	
	/**
	 * 일지 기기류 정보 저장
	 * @param vo
	 * @throws Exception
	 */
	public void insertDailyMachineLog(DailyVO vo) throws Exception{
		int machinePk = Integer.parseInt(dailyDAO.selectDailyMachineLogPk(vo.getSdl_dlog_key()));
		for(int i=0;i<vo.getDailyMachineVOList().size();i++){
			vo.getDailyMachineVOList().get(i).setScm_macn_key(String.valueOf(machinePk+i));
		}
		dailyDAO.insertDailyMachineLog(vo);
	}
	
	/**
	 * 일지 정보 수정
	 */
	public void updateDailyLog(DailyVO vo) throws Exception{
		String rootPath = propertiesService.getString("file.root.path");
		if(vo.getSdl_dlog_file().indexOf("/") == -1 && EgovStringUtil.isNotEmpty(vo.getSdl_dlog_file())){	
			String filePath = dailyDAO.selectDailyAttachFile(vo.getSdl_dlog_key());
			if(EgovStringUtil.isNotEmpty(filePath)){
				FileUtil.deleteFile(rootPath+getAttachFileSplit(filePath)[0]);
			}
			vo.setSdl_dlog_file(this.dailyFilemove(vo));
		}
		dailyDAO.updateDailyLog(vo);
		
		List<InvenVO> dailyInvenLogList = dailyDAO.selectDailyInvenLogList(vo.getSdl_dlog_key());
		List<DailyMachineVO> dailyMachineLogList = dailyDAO.selectDailyMachineLogList(vo.getSdl_dlog_key());
		
		/**
		 * 기기류 변동이 있다면 삭제후 재입력
		 */
		boolean invenModiChk = false;
		if(vo.getInvenVOList().size() != dailyInvenLogList.size()){
			invenModiChk = true;
		}else{
			for(int i=0;i<dailyInvenLogList.size();i++){
				InvenVO db = dailyInvenLogList.get(i);
				InvenVO paramVO = vo.getInvenVOList().get(i);
				if(!EgovStringUtil.null2string(db.getSui_use_num(),"").equals(paramVO.getSui_use_num())){
					invenModiChk = true;
					break;
				}
				if(!EgovStringUtil.null2string(db.getSui_in_num(),"").equals(paramVO.getSui_in_num())){
					invenModiChk = true;
					break;
				}
				if(!EgovStringUtil.null2string(db.getSui_use_note(),"").equals(paramVO.getSui_use_note())){
					invenModiChk = true;
					break;
				}
			}
		}
		if(invenModiChk){
			dailyDAO.deleteDailyInven(vo.getSdl_dlog_key());
			this.insertDailyInvenLog(vo);
		}
		/**
		 * 기기류 변동이 있다면 삭제후 재입력
		 */
		boolean machineModiChk = false;
		if(vo.getDailyMachineVOList().size() != dailyMachineLogList.size()){
			machineModiChk = true;
		}else{
			for(int i=0;i<dailyMachineLogList.size();i++){
				DailyMachineVO db = dailyMachineLogList.get(i);
				DailyMachineVO paramVO = vo.getDailyMachineVOList().get(i);
				if(!EgovStringUtil.null2string(db.getScm_check_name(),"").equals(paramVO.getScm_check_name())){
					machineModiChk = true;
					break;
				}
				if(!EgovStringUtil.null2string(db.getScm_check_result(),"").equals(paramVO.getScm_check_result())){
					machineModiChk = true;
					break;
				}
				if(!EgovStringUtil.null2string(db.getScm_check_note(),"").equals(paramVO.getScm_check_note())){
					machineModiChk = true;
					break;
				}
			}
		}
		if(machineModiChk){
			dailyDAO.deleteDailyMachine(vo.getSdl_dlog_key());
			this.insertDailyMachineLog(vo);
		}
	}
	/**
	 * 일지 정보 삭제(DB 삭제) 사용안함.
	 */
	public void updateStatusDailyLog(DailyVO vo) throws Exception{
		dailyDAO.updateStatusDailyLog(vo);
	}
	
	/**
	 * 일지정보 리스트 및 전체 카운트
	 */
	public Map selectDailyLogList(DailyVO vo) throws Exception{
		Map resultMap = new HashMap();
		resultMap.put("resultList", dailyDAO.selectDailyList(vo));
		resultMap.put("resultListCnt", dailyDAO.selectDailyListCnt(vo));
		return resultMap;
	}
	/**
	 * 일지정보 리스트 및 전체 카운트
	 */
	public Map selectDailyOtherInfo() throws Exception{
		Map resultMap = new HashMap();
		resultMap.put("serviceareaList", serviceareaService.selectServiceAreaList());
		return resultMap;
	}
	/**
	 * 약품 현황 초기값.
	 */
	public List selectDailyFirstInven() throws Exception{
		return dailyDAO.selectDailyFirstInven();
	}
	/**
	 * 일지정보 조회
	 */
	public DailyVO selectDailyLog(DailyVO vo) throws Exception{
		return appendPreData(dailyDAO.selectDailyLog(vo));
	}
	
	public DailyVO appendPreData(DailyVO vo) throws Exception{
		DailyPreVO dailyPreVo = dailyDAO.selectDailyPreLog(vo);
		
		if(dailyPreVo != null){
			String electNumber = dailyPreVo.getSdl_elect_number();
			String iflowDwater = dailyPreVo.getSdl_iflow_dwater();
			String oflowDwater = dailyPreVo.getSdl_oflow_dwater();
			
			List<InvenVO> invenVOList = dailyPreVo.getInvenVOList();
			
			if(EgovStringUtil.isEmpty(electNumber)) electNumber = "0";
			if(EgovStringUtil.isEmpty(iflowDwater))	iflowDwater = "0";
			if(EgovStringUtil.isEmpty(oflowDwater)) oflowDwater = "0";
			
			if(invenVOList != null && vo.getInvenVOList() != null){
				for(InvenVO invenVO : vo.getInvenVOList()){
					for(InvenVO preInvenVO : invenVOList){
						if(invenVO.getSui_code_key().equals(preInvenVO.getSui_code_key())){
							String totalStock = preInvenVO.getSui_total_stock();
							if(EgovStringUtil.isEmpty(totalStock)) totalStock = "0";
							invenVO.setPre_sui_total_stock(totalStock);
						}
					}
					if(EgovStringUtil.isEmpty(invenVO.getPre_sui_total_stock())){
						invenVO.setPre_sui_total_stock("0");
					}
				}
			}
			
			vo.setPre_sdl_elect_number(electNumber); // 전일 전력
			vo.setPre_sdl_iflow_dwater(iflowDwater); // 전일 유입량
			vo.setPre_sdl_oflow_dwater(oflowDwater); // 전일 방류량
		}else{
			vo.setPre_sdl_elect_number("0"); // 전일 전력
			vo.setPre_sdl_iflow_dwater("0"); // 전일 유입량
			vo.setPre_sdl_oflow_dwater("0"); // 전일 방류량
			
			for(InvenVO invenVO : vo.getInvenVOList()){
				invenVO.setPre_sui_total_stock("0");
			}
		}
		return vo;
	}
	/**
	 * chart 용 데이터
	 */
	public List selectDailyChart(DailyVO vo) throws Exception{
		return dailyDAO.selectDailyChart(vo);
	}
	
	/**
	 * chart 용 데이터
	 */
	public List selectDailySludge(DailyVO vo) throws Exception{
		return dailyDAO.selectDailySludge(vo);
	}
	
	/**
	 * 업무연락 첨부파일 이동
	 */
	public String dailyFilemove(DailyVO vo){
		String realPath = propertiesService.getString("file.real.path");
		String tempPath = propertiesService.getString("file.temp.path");
		String[] fileInfo = getAttachFileSplit(vo.getSdl_dlog_file());
		return FileUtil.moveFiles(tempPath, realPath, fileInfo[0])+"**"+fileInfo[1]+"**"+fileInfo[2];
	}
	
	/**
	 * 첨부파일 삭제
	 */
	public boolean deleteDailyAttachFile(String sdl_dlog_key) {
		String rootPath = propertiesService.getString("file.root.path");
		String attachFilePath = "";
		try {
			attachFilePath = dailyDAO.selectDailyAttachFile(sdl_dlog_key);
			FileUtil.deleteFile(rootPath+getAttachFileSplit(attachFilePath)[0]);
			dailyDAO.deleteDailyAttachFile(sdl_dlog_key);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	
	/**
	 * 첨부파일 자르기
	 */
	public String[] getAttachFileSplit(String attachFile){
		String[] result = new String[3];
		String[] temp = attachFile.split("\\*\\*");
		for(int i=0; i<result.length;i++){
			result[i] = temp[i]==null?"":temp[i];
		}
		return result;
	}
}
